/**
 * 豆包AI对话服务
 * 使用豆包API实现AI文本回复功能
 */

export interface DoubaoMessage {
    role: 'user' | 'assistant' | 'system';
    content: string;
}

export interface DoubaoResponse {
    choices: Array<{
        message: {
            content: string;
            role: string;
        };
        finish_reason: string;
        index: number;
    }>;
    created: number;
    id: string;
    model: string;
    object: string;
    usage: {
        completion_tokens: number;
        prompt_tokens: number;
        total_tokens: number;
    };
}

export interface DoubaoConfig {
    apiKey: string;
    apiUrl: string;
    model: string;
}

class DoubaoChatService {
    private config: DoubaoConfig;
    private isConnected: boolean = false;
    private lastRequestTime: number = 0;
    private requestQueue: Array<() => Promise<void>> = [];
    private isProcessingQueue: boolean = false;
    private readonly MIN_REQUEST_INTERVAL = 2000; // 最小请求间隔2秒

    constructor(config: DoubaoConfig) {
        this.config = config;
    }

    /**
     * 发送消息到豆包API（带频率限制）
     */
    async sendMessage(userMessage: string): Promise<string> {
        return new Promise((resolve, reject) => {
            const requestFn = async () => {
                try {
                    const result = await this.executeRequest(userMessage);
                    resolve(result);
                } catch (error) {
                    reject(error);
                }
            };

            this.requestQueue.push(requestFn);
            this.processQueue();
        });
    }

    /**
     * 执行实际的API请求
     */
    private async executeRequest(userMessage: string): Promise<string> {
        try {
            console.log('🚀 发送消息到豆包API:', userMessage);

            const response = await fetch(this.config.apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${this.config.apiKey}`
                },
                body: JSON.stringify({
                    model: this.config.model,
                    messages: [
                        {
                            role: 'user',
                            content: userMessage
                        }
                    ],
                    temperature: 0.7,
                    max_tokens: 1000
                })
            });

            if (!response.ok) {
                if (response.status === 429) {
                    throw new Error(`请求过于频繁，请稍后再试 (${response.status})`);
                }
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data: DoubaoResponse = await response.json();
            console.log('✅ 豆包API响应:', data);

            if (data.choices && data.choices.length > 0) {
                const aiResponse = data.choices[0].message.content;
                console.log('🤖 AI回复:', aiResponse);
                return aiResponse;
            } else {
                throw new Error('API响应格式错误');
            }

        } catch (error) {
            console.error('❌ 豆包API调用失败:', error);
            throw error;
        }
    }

    /**
     * 处理请求队列
     */
    private async processQueue(): Promise<void> {
        if (this.isProcessingQueue || this.requestQueue.length === 0) {
            return;
        }

        this.isProcessingQueue = true;

        while (this.requestQueue.length > 0) {
            const now = Date.now();
            const timeSinceLastRequest = now - this.lastRequestTime;

            if (timeSinceLastRequest < this.MIN_REQUEST_INTERVAL) {
                const waitTime = this.MIN_REQUEST_INTERVAL - timeSinceLastRequest;
                console.log(`⏳ 等待 ${waitTime}ms 后发送请求...`);
                await new Promise(resolve => setTimeout(resolve, waitTime));
            }

            const requestFn = this.requestQueue.shift();
            if (requestFn) {
                try {
                    await requestFn();
                    this.lastRequestTime = Date.now();
                } catch (error) {
                    console.error('❌ 队列请求失败:', error);
                }
            }
        }

        this.isProcessingQueue = false;
    }

    /**
     * 测试API连接
     */
    async testConnection(): Promise<boolean> {
        try {
            console.log('🔍 测试豆包API连接...');
            const response = await this.sendMessage('你好，请回复"连接成功"');
            this.isConnected = response.includes('连接成功') || response.length > 0;
            console.log('✅ 豆包API连接测试:', this.isConnected ? '成功' : '失败');
            return this.isConnected;
        } catch (error) {
            console.error('❌ 豆包API连接测试失败:', error);
            this.isConnected = false;
            return false;
        }
    }

    /**
     * 获取连接状态
     */
    isConnectionActive(): boolean {
        return this.isConnected;
    }

    /**
     * 重置连接状态
     */
    resetConnection(): void {
        this.isConnected = false;
    }
}

// 创建全局实例
export const doubaoChatService = new DoubaoChatService({
    apiKey: '4298c743-c422-4fc8-8ac2-e3c09bee1d1a',
    apiUrl: 'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
    model: 'doubao-seed-1-6-250615'
});

// 导出类
export { DoubaoChatService };
export default DoubaoChatService;
